<?php
declare (strict_types = 1);

namespace app\adminapi\controller;

use think\Exception;
use think\facade\Validate;
use think\Request;

class Image
{
    /**
     * 单图片上传
     */
    public function singleUpload(){
        try {
            //        halt(\request()->param());//param接收不到文件上传的信息
//        halt(\request()->all()); //或者用file方法
            # 验证验证数据

            $image = \request()->file('image');
            $path = \think\facade\Filesystem::disk('public')->putFile( 'images', $image);

            return success(['path' => $path]);
        }catch (Exception $exception) {
            return  error($exception->getMessage(),$exception->getCode());
        }

    }

    /**
     * 多图片上传
     */
    public function multiUpload(){
        try {
            $files = \request()->file('image');//接收所有
            # 存储图片的路径
            $success = [];
            $fail = [];
            # 循环实现上传
            foreach ($files as $file) {
                # 图片验证 大小、类型、后缀
                $validate = Validate::rule([
                    'image'=> 'require|fileExt:png,jpeg,jpg'
                ])->message([
                    'image.require' => "图片信息必填",
                    'image.fileExt' => "图片后缀不允许"
                ]);
                if (!$validate->check(['image' => $file])) {
                    $fail[] = [
                        'name' => $file->getOriginalName(),
                        'reason' => $validate->getError(),//错误原因
                    ];
                } else {
                    $success[] = \think\facade\Filesystem::disk('public')->putFile( 'images', $file);
                }

            }
            return success(['success' => $success,'fail' => $fail]);
        }catch (\Exception $exception) {
            return  error($exception->getMessage(),$exception->getCode());
        }

    }
}
